package jasmine.orm.db.adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;

import jasmine.orm.code.DbContext;
import jasmine.orm.query.Field;
import jasmine.orm.query.Query;

public class UpdateBatchDbOperationAdapter<T> extends AbstractDbOperationAdapter<T>{

	public UpdateBatchDbOperationAdapter(DbContext dbContext, Query<T> query) {
		super(dbContext, query);
		if(tableMapping.isCache()) {
			this.query.cache("",tableMapping.getCacheTime());
		}
	}

	@Override
	public Object cacheAdapter() {
		
		List<String> keys = query.getFiledBatch()
				.stream()
				.map(data->query.getCacheKey(data.get(tableMapping.getPrimaryKey()).toString()))
				.distinct()
				.collect(Collectors.toList());
		cacheOperation.delete(keys);
		return dbAdapter();
	}

	@Override
	public Object dbAdapter() {
		String updateSQL = query.getQueryBuilder().buildBatchUpdateSQL();
		List<Map<String,Field>> batch = query.getFiledBatch();
		String id = tableMapping.getPrimaryKey();
		List<List<Object>> params = batch.stream().map(x->{
			if(!x.containsKey(id)) {
				return null;
			}
			List<Object> values = new ArrayList<Object>(x.size());
			x.forEach((k,v)->{
				if(!k.equals(id)) {
					values.add(v.getValue());
				}
			});
			values.add(x.get(id).getValue());
			return values;
		}).filter(x->x!=null).collect(Collectors.toList());
		if(log.isInfoEnabled() && context.isShowSql()) {
			log.info("==> execute [sql={},params={}]",updateSQL,params);
		}
		return dbOperation.batchUpdate(updateSQL,params.stream().map(x->x.toArray()).collect(Collectors.toList()));
	}




}
